﻿using Ding.IdGenerators.Abstractions;
using Ding.IdGenerators.Core;
using System;

namespace Ding.Helpers {
    /// <summary>
    /// Id 生成器
    /// </summary>
    public static class Id
    {
        /// <summary>
        /// Id
        /// </summary>
        private static string _id;

        /// <summary>
        /// Guid 生成器
        /// </summary>
        public static IGuidGenerator GuidGenerator { get; set; } = SequentialGuidGenerator.Current;

        /// <summary>
        /// Long 生成器
        /// </summary>
        public static ILongGenerator LongGenerator { get; set; } = SnowflakeIdGenerator.Current;

        /// <summary>
        /// String 生成器
        /// </summary>
        public static IStringGenerator StringGenerator { get; set; } = TimestampIdGenerator.Current;

        /// <summary>
        /// 设置Id
        /// </summary>
        /// <param name="id">Id</param>
        public static void SetId(string id) => _id = id;

        /// <summary>
        /// 重置Id
        /// </summary>
        public static void Reset() => _id = null;

        /// <summary>
        /// 创建标识
        /// </summary>
        public static string ObjectId() {
            return string.IsNullOrWhiteSpace( _id ) ? Ding.IdGenerators.Ids.ObjectId.GenerateNewStringId() : _id;
        }

        /// <summary>
        /// 用Guid创建标识,去掉分隔符
        /// </summary>
        public static string Guid() => string.IsNullOrWhiteSpace(_id) ? System.Guid.NewGuid().ToString("N") : _id;

        /// <summary>
        /// 获取Guid
        /// </summary>
        public static Guid GetGuid() => string.IsNullOrWhiteSpace(_id) ? System.Guid.NewGuid() : _id.ToGuid();

        /// <summary>
        /// 创建有序 Guid ID
        /// </summary>
        public static Guid SequentialGuid() => GuidGenerator.Create();

        /// <summary>
        /// 创建 Long ID
        /// </summary>
        public static long GetLong() => LongGenerator.Create();

        /// <summary>
        /// 创建 String ID
        /// </summary>
        public static string GetString() => StringGenerator.Create();

        /// <summary>
        /// 获取13位Id字符串
        /// </summary>
        public static string GetIdString() => IDGenerator.Instance.Generate;

        /// <summary>
        /// 生成sessionid
        /// </summary>
        public static string GenerateSid()
        {
            long i = 1;
            byte[] byteArray = System.Guid.NewGuid().ToByteArray();
            foreach (byte b in byteArray)
            {
                i *= b + 1;
            }
            return string.Format("{0:x}", i - DateTime.Now.Ticks);
        }
    }
}
